<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
          <el-input v-model="listQuery[0].value" clearable class="filter-item" placeholder="登录用户名"
                    @keyup.enter.native="fetchListData"></el-input>
          <el-input v-model="listQuery[2].value" clearable class="filter-item" placeholder="真实姓名"
                    @keyup.enter.native="fetchListData"></el-input>
          <el-select v-model="listQuery.status" clearable class="filter-item" placeholder="状态">
            <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
          <el-input v-model="listQuery[10].value" clearable class="filter-item" placeholder="手机号"
                    @keyup.enter.native="fetchListData"></el-input>
          <el-input v-model="listQuery[11].value" clearable class="filter-item" placeholder="邮箱"
                    @keyup.enter.native="fetchListData"></el-input>
          <el-date-picker v-model="listQuery[12].value" clearable class="filter-item-time"
                          format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" @change="fetchListData"
                          type="daterange" range-separator=" - " start-placeholder="创建开始"
                          end-placeholder="创建结束"></el-date-picker>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="text-align: right">
          <el-button v-waves class="filter-button" icon="el-icon-back" @click="$router.back()">返回
          </el-button>
          <el-button v-waves type="primary" class="filter-button" icon="el-icon-search"
                     @click="fetchListData">搜索
          </el-button>
          <el-button v-waves type="primary" class="filter-button" icon="el-icon-edit"
                     v-permission="['security:sysUser:add']" @click="handleCreateSysUser">新建
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <base-list ref="table" url="/security/sysUser" :query="listQuery" :columns="columns" :format="format">
        <template slot="status" slot-scope="scope">
          <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
          <el-tag v-if="scope.row.status === 2" type="warning">禁用</el-tag>
        </template>
        <template slot="sysDepartmentIds" slot-scope="scope">
          <el-cascader placeholder="无"
            v-model="scope.row.sysDepartmentIds" disabled class="filter-item" :options="sysDepartmentOptions" :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
          ></el-cascader>
        </template>
        <template slot="actions" slot-scope="scope">
          <el-button v-waves @click="handleDetailSysUser(scope.$index, scope.row)">详情
          </el-button>
          <el-button v-waves v-permission="['security:sysUser:edit']" type="primary"
                     @click="handleEditSysUser(scope.$index, scope.row)">编辑
          </el-button>
          <el-button v-waves v-if="scope.row.status === 1" v-permission="['security:sysUser:disable']"
                     type="warning" @click="handleStatusSysUser(scope.row.id, 2)">禁用
          </el-button>
          <el-button v-waves v-if="scope.row.status === 2" v-permission="['security:sysUser:enable']"
                     type="success" @click="handleStatusSysUser(scope.row.id, 1)">启用
          </el-button>
          <el-button v-waves v-permission="['security:sysUser:reset']"
                     type="info" @click="handleResetSysUser(scope.$index, scope.row)">重置密码
          </el-button>
          <el-button v-waves v-permission="['security:sysUser:delete']" type="danger"
                     @click="handleDeleteSysUser(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </base-list>
      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="createDialogVisible"
                 :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" label-suffix=": " :inline="true">
          <el-form-item label="头像" prop="avatar">
            <upload-image class="form-item" :ref="'avatar'" @uploadSuccess="mediaChange" :fileUrl="temp.avatar"
                          columnName="avatar"></upload-image>
          </el-form-item>
          <br>
          <el-form-item label="用户名" prop="username">
            <el-input clearable class="form-item" v-model="temp.username" placeholder="登录用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input clearable class="form-item" v-model="temp.password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input clearable class="form-item" v-model="temp.realName" placeholder="真实姓名"></el-input>
          </el-form-item>
          <el-form-item label="账号过期" prop="accountExpiredTime">
            <el-date-picker clearable class="form-item"
                            v-model="temp.accountExpiredTime" type="datetime" format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss" placeholder="账号过期时间"></el-date-picker>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select clearable class="form-item" v-model="temp.status" placeholder="状态">
              <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input clearable class="form-item" v-model="temp.phone" placeholder="手机号"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input clearable class="form-item" v-model="temp.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="sysRoleIds">
            <el-select clearable class="form-item" v-model="temp.sysRoleIds" placeholder="请选择角色" multiple>
              <el-option v-for="item in sysRoleOptions" :key="item.id" :label="item.authority" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="部门" prop="sysDepartmentIds">
            <el-cascader
              v-model="temp.sysDepartmentIds" placeholder="请选择部门" :options="sysDepartmentOptions" clearable class="form-item"
              :props="{ multiple: true, checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
              ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-waves @click="createDialogVisible = false">取消</el-button>
          <el-button v-waves type="primary" v-permission="['security:sysUser:add' || 'sysUser:edit ']"
                     @click="dialogStatus==='create'?handleAddSysUser():handleUpdateSysUser()">提交
          </el-button>
        </div>
      </el-dialog>
      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="detailDialogVisible"
                 :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <form-detail ref="detailForm" :columns="detailColumns" :dataForm="temp" :format="format"></form-detail>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import waves from '@/directive/waves' // waves directive
import { create as createSysUser, update as updateSysUser, deleteById as deleteSysUser, updateSate as setSysUserState, resetPassword } from '@/api/security/sysUser'
import {getOptions as getSysRoleOptions} from '@/api/security/sysRole'
import {getOptions as getSysDepartmentOptions} from '@/api/security/sysDepartment'
import {mapGetters} from 'vuex'
import BaseList from '@/components/BaseList'
import UploadImage from '@/components/UploadImage'
import FormDetail from '@/components/FormDetail'

export default {
  name: 'SysUser',
  components: {BaseList, UploadImage, FormDetail},
  directives: {permission, waves},
  data() {
    return {
      list: null,
      columns: [
        {key: 'index', label: '编号', width: 40, fixed: 'left'},
        {key: 'username', label: '用户名', width: 100},
        {key: 'realName', label: '真实姓名', width: 100},
        {key: 'sysRoleIds', label: '角色', width: 200},
        {key: 'sysDepartmentIds', label: '部门', width: 300},
        {key: 'lastLoginTime', label: '最后登录时间', sortable: true, width: 200},
        {key: 'lastModifyPasswordTime', label: '最后修改密码', sortable: true, width: 200},
        {key: 'passwordErrorTimes', label: '密码错误次数', width: 200},
        {key: 'accountLockTime', label: '锁定时间', sortable: true, width: 200},
        {key: 'accountExpiredTime', label: '账号过期时间', sortable: true, width: 200},
        {key: 'status', label: '状态', sortable: true, type: 'status', width: 100},
        {key: 'avatar', label: '头像', width: 200, type: 'image'},
        {key: 'phone', label: '手机号', width: 200},
        {key: 'email', label: '邮箱', width: 200},
        {key: 'createTime', label: '创建时间', sortable: true, width: 200},
        {key: 'actions', label: '操作', width: 480, fixed: 'right', align: 'left'}
      ],
      detailColumns: [
        {
          label: '', columns: [
            {key: 'username', label: '用户名'},
            {key: 'realName', label: '真实姓名'},
            {key: 'lastLoginTime', label: '最后登录'},
            {key: 'lastModifyPasswordTime', label: '最后修改'},
            {key: 'passwordErrorTimes', label: '密码错误'},
            {key: 'accountLockTime', label: '锁定时间'},
            {key: 'accountExpiredTime', label: '账号过期'},
            {key: 'status', label: '状态'},
            {key: 'avatar', label: '头像', type: 'image'},
            {key: 'phone', label: '手机号'},
            {key: 'email', label: '邮箱'},
            {key: 'createTime', label: '创建时间'},
          ]
        }
      ],
      format: {
        index: (data, index) => {
          return index + 1
        },
        sysRoleIds: (data, index) => {
          return data.sysRoleIds && data.sysRoleIds.length > 0 ? this.sysRoleOptions.filter(o => data.sysRoleIds.includes(o.id)).map(o => o.authority).join(',') : '无'
        }
      },
      listQuery: [
        {column: 'username', condition: 'like', value: null},
        {column: 'password', condition: 'like', value: null},
        {column: 'realName', condition: 'like', value: null},
        {column: 'lastLoginTime', condition: 'bt', value: null},
        {column: 'lastModifyPasswordTime', condition: 'bt', value: null},
        {column: 'passwordErrorTimes', condition: '=', value: null},
        {column: 'accountLockTime', condition: 'bt', value: null},
        {column: 'accountExpiredTime', condition: 'bt', value: null},
        {column: 'status', condition: '=', value: null},
        {column: 'avatar', condition: 'like', value: null},
        {column: 'phone', condition: 'like', value: null},
        {column: 'email', condition: 'like', value: null},
        {column: 'createTime', condition: 'bt', value: null}
      ],
      temp: {
        username: undefined,
        password: undefined,
        realName: undefined,
        lastLoginTime: undefined,
        lastModifyPasswordTime: undefined,
        passwordErrorTimes: undefined,
        accountLockTime: undefined,
        accountExpiredTime: undefined,
        status: undefined,
        avatar: undefined,
        phone: undefined,
        email: undefined,
        sysRoleIds: [],
        sysDepartmentIds:[]
      },
      statusOptions: [{id: 1, name: '启用'}, {id: 2, name: '禁用'}],
      dialogTextMap: {update: '编辑', create: '新建', detail: '详情'},
      rules: {
        username: [{required: true, message: '用户名必填!', trigger: 'blur'}],
        realName: [{required: true, message: '真实姓名必填!', trigger: 'blur'}],
        status: [{required: true, message: '状态必填!', trigger: 'change'}],
        phone: [{required: true, message: '手机号必填!', trigger: 'blur'}],
        email: [{required: true, message: '邮箱必填!', trigger: 'blur'}],
        sysRoleIds: [{required: true, message: '角色必填!', trigger: 'change'}],
        sysDepartmentIds: [{required: true, message: '部门必填!', trigger: 'change'}],
      },
      dialogStatus: '',
      createDialogVisible: false,
      detailDialogVisible: false,
      sysRoleOptions: [],
      sysDepartmentOptions: []
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    const allOptions = JSON.parse(localStorage.getItem('allOptions'))
    this.handleGetSysRoleOptions()
  },
  mounted() {
    this.fetchListData()
  },
  methods: {
    fetchListData() {
      this.$refs.table.fetchData(1)
    },
    reloadListData() {
      this.$refs.table.fetchData()
    },
    resetTemp() {
      this.temp = {
        username: undefined,
        password: undefined,
        realName: undefined,
        lastLoginTime: undefined,
        lastModifyPasswordTime: undefined,
        passwordErrorTimes: undefined,
        accountLockTime: undefined,
        accountExpiredTime: undefined,
        status: 1,
        avatar: undefined,
        phone: undefined,
        email: undefined,
      }
    },
    handleGetSysRoleOptions() {
      getSysRoleOptions().then(res => {
        this.sysRoleOptions = res.data
      })
      getSysDepartmentOptions().then(res => {
        this.sysDepartmentOptions = res.data
      })
    },
    mediaChange(val, index, column) {
      this.temp[column] = val;
    },
    handleCreateSysUser() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDetailSysUser(index, val) {
      this.temp = Object.assign({}, val)
      this.dialogStatus = 'detail'
      this.detailDialogVisible = true
    },
    handleEditSysUser(index, val) {
      this.temp = Object.assign({}, val)
      this.dialogStatus = 'update'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddSysUser() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const queryData = Object.assign({}, this.temp)
          queryData.status = Number(queryData.status)
          createSysUser(queryData).then(() => {
            // this.list.unshift(queryData)
            this.fetchListData()
            this.createDialogVisible = false
            this.$notify.success('管理员创建成功!')
          })
        }
      })
    },
    handleUpdateSysUser() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateSysUser(tempData).then(() => {
            this.reloadListData()
            this.createDialogVisible = false
            this.$notify.success('管理员更新成功!')
          })
        }
      })
    },
    handleDeleteSysUser(index, val) {
      const self = this
      this.$confirm('确定要删除该管理员？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSysUser(val.id).then(() => {
          self.reloadListData()
          self.$notify.success('管理员已删除!')
        })
      }).catch(() => {
      })
    },
    handleStatusSysUser(id, status) {
      const self = this
      this.$confirm('确定要' + ['', '启用', '禁用'][status] + '该管理员？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        setSysUserState(id, status).then(() => {
          self.createDialogVisible = false
          self.reloadListData()
          self.$notify.success('管理员' + ['', ' 已启用!', '已禁用!'][status])
        })
      }).catch(() => {
        return
      })
    },
    handleResetPassword(index, val) {
      const self = this
      this.$confirm('确定要重置该用户密码吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPassword({id: val.id}).then(res => {
          self.$notify.success('用户 ' + val.realName + ' 密码重置成功! 新密码为:' + res.data)
        })
      }).catch(() => {
      })
    }
  }
}
</script>

